/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-13 23:44:25
 * @Last modified by:   ls-mac
 * @Last modified time: 2019-08-27 22:31:42
 */

import {
  dictInstitutionPage,
  dictInstitutionList,
  dictInstitutionAddOrEdit,
  dictInstitutionDelete,
} from 'services/dict';

export default {
  namespace: 'institutionList',
  state: {
    data: {
      list: [],
      pagination: {},
    },
    dictInstitutionList: [],
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(dictInstitutionPage, payload);
      yield put({
        type: 'saveList',
        payload: response,
      });
    },
    *dictInstitutionList({ payload }, { call, put }) {
      const response = yield call(dictInstitutionList, payload);
      yield put({
        type: 'saveDictInstitutionList',
        payload: response,
      });
    },
    *dictInstitutionAddOrEdit({ payload, callback }, { call, put }) {
      const response = yield call(dictInstitutionAddOrEdit, payload);
      if (callback) {
        callback(response);
      }
    },
    *dictInstitutionAddOrEdit({ payload, callback }, { call, put }) {
      const response = yield call(dictInstitutionAddOrEdit, payload);
      if (callback) {
        callback(response);
      }
    },
    *dictInstitutionDelete({ payload, callback }, { call, put }) {
      const response = yield call(dictInstitutionDelete, payload);
      if (callback) {
        callback(response);
      }
    },
  },

  reducers: {
    saveList(state, action) {
      const {
        data: { institutionList, pageIndex, pageSize, recordCount },
      } = action.payload;

      const newList = institutionList.map(v => {
        v.key = `k${v.id}`;
        return v;
      });
      return {
        ...state,
        data: {
          list: newList,
          pagination: {
            current: pageIndex,
            total: recordCount,
            pageSize,
          },
        },
      };
    },

    saveDictInstitutionList(state, action) {
      const { data } = action.payload;
      const newList = data.map(val => {
        const v = val;
        v.key = `k${v.id}`;
        return v;
      });
      return {
        ...state,
        dictInstitutionList: newList,
      };
    },
  },
};
